<template>
  <div>
    <div class="form-container">
      <el-form
        :model="classInfo"
        label-width="auto"
        style="max-width: 300px"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item
          ><h1 style="font-size: 30px; margin-left: 100px">
            创建班级
          </h1></el-form-item
        >
        <el-form-item label="班级名" prop="name">
          <el-input v-model="classInfo.name" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="classInfo.balance"></el-input>
        </el-form-item>
        <el-button
          type="primary"
          @click="createClass()"
          style="margin-left: 20px"
          >提交</el-button
        >
        <el-button
          type="warning"
          @click="resetClass()"
          style="margin-left: 30px"
          >重置</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { createClassApi } from '@src/apis/classApi.ts'
import { TypeClassInfo } from '@src/interfaces/TypeClassInfo.ts'
import { onMounted, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { router } from '@util/RouterUtil.ts'
import TokenUtil from '@util/TokenUtil.ts'
import useUserStore from '@src/stores/useUserStore.ts'

const classInfo = ref({
  name: '',
  size: 1,
  status: '正常',
  balance: 0,
} as TypeClassInfo)

const formRef = ref<FormInstance>()

const rules = ref<FormRules<typeof classInfo>>({
  name: [
    { required: true, message: '请输入班级名！', trigger: 'blur' },
    {
      validator: (_, value: string, callback) => {
        const regular = /^.{1,11}$/
        if (!regular.test(value.trim())) {
          callback(new Error('长度为4-11位'))
          return
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
  balance: [
    { required: true, message: '请输入余额！', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        // 尝试将输入转换为数字，并处理非数字输入
        const numValue = Number(value)
        if (isNaN(numValue)) {
          callback(new Error('余额必须是一个有效的数字！'))
          return
        }

        // 验证余额的最小值（例如，不允许负数或零）
        if (numValue < 0) {
          callback(new Error('余额必须为非负数！'))
          return
        }

        callback()
      },
      trigger: 'blur',
    },
  ],
})

function resetClass() {
  classInfo.value = {
    name: '',
    size: 1,
    status: '正常',
    balance: 0,
  }
}

function createClass() {
  formRef.value?.validate((value) => {
    if (!value) {
      return
    }
    createClassApi(classInfo.value).then(() => {
      ElMessage.success('创建成功！')
      toClassInfo()
    })
  })
}

function toClassInfo() {
  router.push('/class/info')
}

onMounted(() => {
  TokenUtil.refresh().then(() => {
    if (useUserStore().userInfo.classId) {
      ElMessage.warning('您已加入班级，无需创建！')
      router.push('/class/info')
      return
    }
  })
})
</script>

<style scoped lang="less">
.form-container {
  display: flex;
  justify-content: center;
  margin-top: 100px;
}

.el-button {
  width: 120px;
}
</style>
